<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row class="buttongap">
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="rolelist" style="width: 100%" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children"
              :key="item1.id">
              <!-- 一级权限展示 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightByid(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限展示 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children"
                  :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag closable @close="removeRightByid(scope.row, item2.id)" type="success">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限展示 -->
                  <el-col :span="18">
                    <el-tag v-for="(item3, i3) in item2.children" :key="item3.id" type="warning" closable
                      @close="removeRightByid(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="deleteUserById(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="用户权限管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="showRightDiglog(scope.row)"
                size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" @close="addDialogClosed" width="50%">
      <el-form :model="addForm" :rules="addRuleForm" ref="addFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="addForm.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roledec">
          <el-input v-model="addForm.roledec"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="editDialogVisible" @close="editDialogClosed" width="50%">
      <el-form :model="editForm" :rules="addRuleForm" ref="editFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="editForm.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roledec">
          <el-input v-model="editForm.roledec"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setdialogVisible" width="30%" @close="setdialogVisibleClose">
      <el-tree :data="relosList" :props="relosListProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="defkeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      rolelist: [],
      addDialogVisible: false,
      addForm: {
        rolename: '',
        roledec: ''
      },
      editDialogVisible: false,
      editForm: {
        id: '',
        rolename: '',
        roledec: ''
      },
      addRuleForm: {
        rolename: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roledec: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 编辑权限对话框
      setdialogVisible: false,
      // 所有权限的数据
      relosList: [],
      // 树形控件的属性绑定对象
      relosListProps: {
        children: 'children',
        label: 'authName'
      },
      // 已经选中的权限
      defkeys: [],
      // 当前设置权限被选中的id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取权限列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error("获取菜单列表失败！")
      this.rolelist = res.data
    },
    // 添加角色
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', { roleName: this.addForm.rolename, roleDesc: this.addForm.roledec })
        if (res.meta.status !== 201) return this.$message.error("添加角色失败")
        this.$message.success("添加用户成功")
        this.addDialogVisible = false
        this.getRoleList()
      })
    },
    // 监听表单关闭重置数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 显示当前用户信息
    async showEditDialog(roleInfo) {
      this.editForm.id = roleInfo.id
      this.editForm.rolename = roleInfo.roleName
      this.editForm.roledec = roleInfo.roleDesc
      this.editDialogVisible = true
      console.log(this.editForm)
    },
    // 监听edit表单关闭重置数据
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改角色信息
    async editRole() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`roles/${this.editForm.id}`,
          {
            roleName: this.editForm.rolename,
            roleDesc: this.editForm.roledec
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('更新角色信息失败!')
        } else {
          this.editDialogVisible = false
          this.getRoleList()
          this.$message.success('更新角色成功!')
        }
      })
    },
    // 删除用户表单
    async deleteUserById(id) {
      const confirmResult = await this.$confirm('是否永久删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户点击确定，返回confirm
      // 点击去取消，返回cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info("取消删除用户操作！")
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败！")
      }
      this.$message.success("删除用户成功！")
      this.getRoleList()
    },
    // 删除角色权限
    async removeRightByid(role, rightId) {
      const confirmResult = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info("取消删除权限操作！")
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error("删除权限失败！")
      }
      this.$message.success("删除权限成功！")
      // 通过传递过来的role，直接将后台换回的最新数据进行替换
      role.children = res.data
    },
    // 展示修改权限
    async showRightDiglog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree ')
      if (res.meta.status !== 200) return this.$message.error("权限列表获取失败")
      this.relosList = res.data
      this.getLeafKeys(role, this.defkeys)
      this.setdialogVisible = true
    },
    // 递归获取该用户已有权限的id数组
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      });
    },
    // 关闭对话框时清空数组
    setdialogVisibleClose() {
      this.defkeys = []
    },
    // 为角色分配权限
    async allotRights() {
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const roleskey = key.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: roleskey })
      if (res.meta.status !== 200) return this.$message.error("分配权限失败！")
      this.$message.success("分配权限成功！")
      this.setdialogVisible = false
      this.getRoleList()
    }
  }
}
</script>

<style class="less" scoped>
.buttongap {
  margin-bottom: 20px;
}

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid rgb(246, 246, 246);
}

.bdbottom {
  border-bottom: 1px solid rgb(246, 246, 246);
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>